#include "login.h"
#include "ui_login.h"
#include "my_register.h"
#include "databasemanager.h"
#include <qmessagebox.h>
#include <QTimer>
login* login::instance=nullptr;

login::login(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::login)
{
    ui->setupUi(this);

    //隐去上边框
    setWindowFlag(Qt::FramelessWindowHint);

    this->installEventFilter(new DragWidgetFilter(this));



}

login::~login()
{
    delete ui;
}

void login::paintEvent(QPaintEvent *event)
{
    QPainter mainPainter(this);
    mainPainter.drawPixmap(rect(),QPixmap(":/login/qq_back.jpeg"),QRect());
}

void login::login_successed(const QString& username,const QString& nickname,const QString& path,const QString& last_login_time)
{
    emit loginSuccess(username,nickname,path,last_login_time);
    my_register::destoryInstance();
    login::destroyInstance();
}

login *login::getInstance()
{
    if(instance==nullptr)
    {
        instance=new login();
    }
    return instance;
}

void login::destroyInstance()
{
    if(instance)
    {
        qDebug()<<"login delete";
        delete instance;
        instance=nullptr;
    }
}

void login::on_radioButton_clicked()
{
    if(ui->radioButton->isChecked()){
        ui->login_pushButton->setStyleSheet("background-color: rgb(0,141,235);");
        ui->login_pushButton->setEnabled(true);
    }
    else {
        ui->login_pushButton->setStyleSheet("background-color: rgb(158,218,255);");
        ui->login_pushButton->setEnabled(false);
    }
}


void login::on_login_pushButton_clicked()
{
    qDebug()<<"登录点击";
    QString username=ui->lineEdit->text();
    QString password=ui->lineEdit_2->text();
    std::tuple<QString,QString,QString> res=DatabaseManager::getInstance().query_login(username,password);
    // qDebug()<<"res="<<res;
    qDebug()<<"res 2="<<std::get<1>(res);
    if(!std::get<0>(res).compare("账号或密码有问题")){
        QMessageBox::critical(NULL,"错误","账号或密码有问题",QMessageBox::Discard);
    }else{
        QMessageBox::information(NULL,"提示",QString("恭喜你 用户名为%1登录成功").arg(std::get<0>(res)),QMessageBox::Apply);
        login_successed(username,std::get<0>(res),std::get<1>(res),std::get<2>(res));
    }
}


void login::on_close_toolButton_clicked()
{
    this->close();
}


void login::on_register_pushButton_clicked()
{
    // emit reg();
    QPoint currentPos=this->pos();

    this->hide();
    my_register* mr=my_register::getInstance();
    mr->move(currentPos);
    mr->show();

}

